//
//  NewsRequest.m
//  Together
//
//  Created by Wang Shuguang on 12-12-14.
//  Copyright (c) 2012年 Dawn. All rights reserved.
//

#import "NewsRequest.h"
static NSMutableArray *sharedQueue = nil;

@interface NewsRequest()
- (id) initWithURL:(NSURL *)url;
@end

@implementation NewsRequest
@synthesize src;
@synthesize delegate;
@synthesize dataDict;
@synthesize saveName;
@synthesize index;
@synthesize newsType;

- (void) dealloc{
    NSLog(@"释放：%@",self.src);
    
    self.src = nil;
    self.dataDict = nil;
    self.saveName = nil;
    [imageArray release];
    [contentArray release];
    [super dealloc];
}

#pragma mark -
#pragma mark 静态初始化函数

+ (void)initialize{
    if (self == [NewsRequest class]) {
        sharedQueue = [[NSMutableArray alloc] initWithCapacity:4];
    }
}

#pragma mark -
#pragma mark 初始化方法
- (id) initWithURL:(NSURL *)url{
    if (self = [super init]) {
        self.src = url;
        imageArray = [[NSMutableArray alloc] initWithCapacity:0];
        contentArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return self;
}

#pragma mark -
#pragma mark Public Method
+ (id) requestWithURL:(NSURL *)url{
    return [[[self alloc] initWithURL:url] autorelease];
}

- (void) requestWithNewsType:(RequestNewsType)requestNewsType{
    self.newsType = requestNewsType;
    
    [self startRequest];
}

- (void) startRequest{
    [sharedQueue addObject:self];
    // 重置图片计数器
    imageCount = 0;
    contentCount = 0;
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:self.src];
    [request setTimeoutInterval:TIMEOUT];
    operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        [self requestFinished:request JSON:JSON];
        
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"%@",error.userInfo);
        [self requestFailed:request];
    }];
    [operation start];
}



- (void) cancelRequest{
    [operation cancel];
}

#pragma mark -
#pragma mark 缓存图片和内容

- (void) beginCache{
    NSLog(@"缓存开始");
    if (newsType == Budejie_Download) {
        NSObject *obj = [self.dataDict objectForKey:@"list"];
        imageCount = 0;
        [imageArray removeAllObjects];
        
        if (obj && obj != [NSNull null]) {
            NSArray *list = (NSArray *)obj;
            for (int i = 0; i < [list count]; i++) {
                NSDictionary *dict = (NSDictionary *)[list objectAtIndex:i];
                if ([dict objectForKey:@"image1"] && [dict objectForKey:@"image1"] != [NSNull null]) {
                    NSString *imageUrlStr = [dict objectForKey:@"image1"];
                    if (![imageUrlStr isEqualToString:@""]) {
                        [imageArray addObject:imageUrlStr];
                    }
                }
            }
        }
    }else if(newsType == NetEasyHeadline_Download){
        NSObject *obj = [self.dataDict objectForKey:self.saveName];
        imageCount = 0;
        contentCount = 0;
        [imageArray removeAllObjects];
        [contentArray removeAllObjects];
        
        if (obj && obj != [NSNull null]) {
            NSArray *list = (NSArray *)obj;
            for (int i = 0; i < [list count]; i++) {
                NSDictionary *dict = (NSDictionary *)[list objectAtIndex:i];
                if ([dict objectForKey:@"imgsrc"] && [dict objectForKey:@"imgsrc"] != [NSNull null]) {
                    NSString *imageUrlStr = [dict objectForKey:@"imgsrc"];
                    if (![imageUrlStr isEqualToString:@""]) {
                        [imageArray addObject:imageUrlStr];
                    }
                }
                [contentArray addObject:[NSString stringWithFormat:@"%@%@/full.html",NETEASYCONTENT,[dict objectForKey:@"docid"]]];
            }
        }
        
    }else if(newsType == Qiubai_Download){
        NSObject *obj = [self.dataDict objectForKey:@"items"];
        imageCount = 0;
        [imageArray removeAllObjects];
        
        if (obj && obj != [NSNull null]) {
            NSArray *list = (NSArray *)obj;
            for (int i = 0; i < [list count]; i++) {
                NSDictionary *dict = (NSDictionary *)[list objectAtIndex:i];
                if ([dict objectForKey:@"image"] && [dict objectForKey:@"image"] != [NSNull null]) {
                    NSString *imageUrlStr = [dict objectForKey:@"image"];
                    if (![imageUrlStr isEqualToString:@""]) {
                        NSString *id = (NSString *)[dict objectForKey:@"id"];
                        imageUrlStr = [NSString stringWithFormat:@"%@%@/%@/small/%@",QIUBAIIMAGEPATH,[id substringToIndex:4],id,[dict objectForKey:@"image"]];
                        [imageArray addObject:imageUrlStr];
                        NSLog(@"%@",imageUrlStr);
                    }
                }
            }
        }
    }
    
    // 先下载图片
    [self downloadImage];
}

- (void) downloadImage{
    
    SDWebImageManager *manager = [SDWebImageManager sharedManager];
	
	if (imageCount < [imageArray count]) {
        NSString *url = [imageArray objectAtIndex:imageCount];
        [manager downloadWithURL:[NSURL URLWithString:url]
                        delegate:self
                         options:SDWebImageLowPriority];
    }else{
        if (newsType != NetEasyHeadline_Download) {
            // 汇报进度
            if ([self.delegate respondsToSelector:@selector(requestProgress:request:)]) {
                [delegate requestProgress:1.0 request:self];
            }
            // 缓存完成
            if ([self.delegate respondsToSelector:@selector(requestFinished:withData:)]) {
                [delegate requestFinished:self withData:self.dataDict];
            }
            // 释放内存中的图片缓存
            SDImageCache *imageCache = [SDImageCache sharedImageCache];
            [imageCache clearMemory];
            
            // 设置缓存时间
            NSUserDefaults* dater = [NSUserDefaults standardUserDefaults];
            [dater setValue:[NSNumber numberWithLongLong:[[NSDate date] timeIntervalSince1970]]
                     forKey:[NSString stringWithFormat:@"%@_UpdateTime",self.saveName]];
            [dater synchronize];
            
            NSLog(@"图片缓存完成");
            
            [sharedQueue removeObject:self];
        }else{
            // 释放内存中的图片缓存
            SDImageCache *imageCache = [SDImageCache sharedImageCache];
            [imageCache clearMemory];
            
            // 开始缓存内容
            [self downloadContent];
        }
    }
}


- (void) downloadContent{
    if (contentCount < [contentArray count]) {
        NSString *contentUrl = [contentArray objectAtIndex:contentCount];
        if ([self checkContentFileExist:contentUrl]) {
            // 下一条
            contentCount = contentCount + 1;
            [self downloadContent];
        }else{
        
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:contentUrl]];
            [request setHTTPMethod:@"GET"];
            [request setTimeoutInterval:TIMEOUT];
            operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                [self requestFinished:request JSON:JSON];
            } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                [self requestFailed:request];
            }];
            [operation start];
        }
    }else{
        // 汇报进度
        if ([self.delegate respondsToSelector:@selector(requestProgress:request:)]) {
            [delegate requestProgress:1.0 request:self];
        }
        // 缓存完成
        if ([self.delegate respondsToSelector:@selector(requestFinished:withData:)]) {
            [delegate requestFinished:self withData:self.dataDict];
        }
        
        // 设置缓存时间
        NSUserDefaults* dater = [NSUserDefaults standardUserDefaults];
        [dater setValue:[NSNumber numberWithLongLong:[[NSDate date] timeIntervalSince1970]]
                 forKey:[NSString stringWithFormat:@"%@_UpdateTime",self.saveName]];
        [dater synchronize];
        
        NSLog(@"内容缓存完成");
        
        [sharedQueue removeObject:self];
    }
    
}

#pragma mark -
#pragma mark 文件操作
- (BOOL) checkContentFileExist:(NSString *)contentUrl{
    // 通过URL取得文件路径
    NSString *cPath = [self getContentPath:contentUrl];
    
    // 检测文件是否存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:cPath]) {
        return YES;
    }else{
        return NO;
    }
}

- (NSString *) getContentPath:(NSString *)contentUrl{
    // 取得URL的MD5值
    
    NSString *filename = [Common keyWithURLString:contentUrl];
    
    // 缓存文件夹路径
    NSString *cPath = [Common cacheFilePath:nil];
    
    // 检测缓存文件夹是否存在，如果不存在就创建
    if (![[NSFileManager defaultManager] fileExistsAtPath:cPath]){
        [[NSFileManager defaultManager] createDirectoryAtPath:cPath
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:NULL];
    }
    
    
    cPath = [Common cacheFilePath:filename];
    return cPath;
}

- (void) saveToFileWithData:(NSData *)data{
    
    // 数据文件夹路径
    
    NSString *cPath = [Common dataFilePath:nil];
    
    // 检测数据文件夹是否存在，如果不存在就创建
    if (![[NSFileManager defaultManager] fileExistsAtPath:cPath]){
        [[NSFileManager defaultManager] createDirectoryAtPath:cPath
                                  withIntermediateDirectories:YES
                                                   attributes:nil
                                                        error:NULL];
    }
    
    cPath = [Common dataFilePath:self.saveName];
   
    BOOL saveFlag = [data writeToFile:cPath atomically:YES];
    if (saveFlag) {
        NSLog(@"成功保存数据文件");
    }else{
        NSLog(@"数据文件保存失败");
    }
    
}

- (void) saveToCacheWithData:(NSData *)data contentUrl:(NSString *)url{
    
    NSString *cPath = [self getContentPath:url];
    
    BOOL saveFlag = [data writeToFile:cPath atomically:YES];
    if (saveFlag) {
        //NSLog(@"成功保存Content文件");
    }else{
        //NSLog(@"Content文件保存失败");
    }
}

#pragma mark -
#pragma mark SDWebImageManagerDelegate
- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image{
     NSLog(@"image download succeed at:%d",imageCount);
    imageCount = imageCount + 1;
   
    // 汇报进度
    if (newsType != NetEasyHeadline_Download) {
        if ([self.delegate respondsToSelector:@selector(requestProgress:request:)]) {
            [delegate requestProgress:((imageCount + 0.0)/[imageArray count]) request:self];
        }
    }else{
        if ([self.delegate respondsToSelector:@selector(requestProgress:request:)]) {
            [delegate requestProgress:((imageCount + contentCount + 0.0)/([imageArray count] + [contentArray count])) request:self];
        }
    }
    [self downloadImage];
}
- (void)webImageManager:(SDWebImageManager *)imageManager didFailWithError:(NSError *)error{
    NSLog(@"image download failed at:%d",imageCount);
    imageCount = imageCount + 1;
    
    // 汇报进度
    if (newsType != NetEasyHeadline_Download) {
        if ([self.delegate respondsToSelector:@selector(requestProgress:request:)]) {
            [delegate requestProgress:((imageCount + 0.0)/[imageArray count]) request:self];
        }
    }else{
        if ([self.delegate respondsToSelector:@selector(requestProgress:request:)]) {
            [delegate requestProgress:((imageCount + contentCount + 0.0)/([imageArray count] + [contentArray count])) request:self];
        }
    }
    [self downloadImage];
}
- (void)webImageManager:(SDWebImageManager *)imageManager didReceivedData:(NSData *)data contentLength:(long long)length{
    
}



-(void) requestFailed:(NSURLRequest *)request{
    NSString *srcUrl = [NSString stringWithFormat:@"%@",self.src];
    NSString *requestUrl = [NSString stringWithFormat:@"%@",request.URL];
    if ([srcUrl isEqualToString:requestUrl]) {
        if ([self.delegate respondsToSelector:@selector(requestFailed:)]) {
            [self.delegate requestFailed:self];
        }
        [sharedQueue removeObject:self];
    }else{
        NSLog(@"content download faild at:%d",contentCount);
        contentCount = contentCount + 1;
        
        if ([self.delegate respondsToSelector:@selector(requestProgress:request:)]) {
            [delegate requestProgress:((imageCount + contentCount + 0.0)/([imageArray count] + [contentArray count])) request:self];
        }
        [self downloadContent];
    }
}

-(void) requestFinished:(NSURLRequest *)request JSON:(id)JSON{
    if (!self.dataDict) {
        //获取数据完成
        if (!JSON) {
            if ([self.delegate respondsToSelector:@selector(requestFailed:)]) {
                [self.delegate requestFailed:self];
            }
        }else {
            NSDictionary *infoDict = (NSDictionary *)JSON;
            
            if(infoDict==NULL || infoDict == nil){
                if ([self.delegate respondsToSelector:@selector(requestFailed:)]) {
                    [self.delegate requestFailed:self];
                }
            }else{
                self.dataDict = infoDict;
                [self saveToFileWithData:operation.responseData];
                if (newsType == Budejie || newsType == BudejieMM || newsType == NetEasyHeadline) {
                    if ([self.delegate respondsToSelector:@selector(requestFinished:withData:)]) {
                        [delegate requestFinished:self withData:self.dataDict];
                    }
                    [sharedQueue removeObject:self];
                }else{
                    // 开始下图
                    [self beginCache];
                }
            }
        }
    }else{
        NSString *url = [NSString stringWithFormat:@"%@",request.URL];
        [self saveToCacheWithData:operation.responseData contentUrl:url];
        NSLog(@"content download succeed at:%d",contentCount);
        contentCount = contentCount + 1;
        if ([self.delegate respondsToSelector:@selector(requestProgress:request:)]) {
            [delegate requestProgress:((imageCount + contentCount + 0.0)/([imageArray count] + [contentArray count])) request:self];
        }
        [self downloadContent];
        
    }
}


@end
